<template>
  <div class="common-layout questionIndex">
    <!-- container-xl containermain bg-white -->
    <el-container class="container-box">
      <el-container class="container-left">
        <el-header class="container-header">
          <el-tabs
            id="p20"
            type="border-card"
            :stretch="stretch"
            v-model="activeName"
            @tab-change="tabChange"
          >
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.public"
              label="编程题库"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.nopublic"
              label="初赛题库"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.team"
              label="团队题库"
            ></el-tab-pane>
            <el-tab-pane
              v-if="showCF(teamId) || showRemotejudge"
              :lazy="true"
              :name="TABSNAME.codeforces"
              label="RemoteJudge"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              v-if="vip"
              :name="TABSNAME.match"
              label="精选题库"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              v-if="isShowAccoder"
              :name="TABSNAME.accoder"
              label="Accoders"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.user"
              label="我的题库"
            ></el-tab-pane>
            <!-- 搜索条件 -->
            <div class="">
              <el-form class="container-header-form" label-position="left">
                <div v-if="tabsCfg[activeName].desc">
                  <div>
                    <el-text size="small" type="info">
                      <el-icon>
                        <InfoFilled />
                      </el-icon>
                      {{ tabsCfg[activeName].desc }}
                    </el-text>
                  </div>
                </div>
                <!-- RemoteJudge -->
                <el-form-item
                  v-show="isRemoteJudge"
                  class="container-header-form-item"
                  size="default"
                  label="题库筛选"
                  :label-width="70"
                >
                  <el-radio-group size="default">
                    <el-button
                      class=""
                      :plain="false"
                      type="primary"
                      size="default"
                    >
                      CODEFORCES
                    </el-button>
                  </el-radio-group>
                </el-form-item>
                <!-- 精选题库-题库来源 -->
                <el-form-item
                  v-if="activeName == TABSNAME.match"
                  class="container-header-form-item"
                  size="default"
                  label="题库来源"
                  :label-width="70"
                >
                  <el-radio-group size="default">
                    <el-button
                      @click="formInline.source = ''"
                      :type="!Boolean(formInline.source) ? 'primary' : 'info'"
                      :plain="!Boolean(formInline.source) ? false : true"
                      size="default"
                    >
                      全部
                    </el-button>
                    <el-button
                      v-for="(value, key) in DATAform"
                      @click="sourceClick(value)"
                      :type="formInline.source === value ? 'primary' : 'info'"
                      :plain="formInline.source === value ? false : true"
                      :key="key"
                      size="default"
                    >
                      {{ key }}
                    </el-button>
                  </el-radio-group>
                </el-form-item>
                <!-- 难度筛选 -->
                <el-form-item
                  class="container-header-form-item"
                  size="default"
                  label="难度筛选"
                  prop="rating"
                  :label-width="70"
                >
                  <!-- CF 难度 -->
                  <div v-if="isVipCF">
                    <el-select
                      id="rating"
                      v-model="formInline.rating"
                      filterable
                      clearable
                      placeholder="选择难度"
                      style="width: 250px"
                    >
                      <el-option
                        v-for="(item, key) in CFdifficulty.length"
                        :key="item"
                        :label="`*${key * 100 + CFdifficulty.start}`"
                        :value="`${key * 100 + CFdifficulty.start}`"
                      />
                    </el-select>
                  </div>
                  <!-- 其他题库 -->
                  <div v-else>
                    <el-button
                      @click="formInline.difficulty = []"
                      :type="
                        !Boolean(formInline.difficulty?.length)
                          ? 'primary'
                          : 'info'
                      "
                      :plain="
                        !Boolean(formInline.difficulty?.length) ? false : true
                      "
                      size="default"
                    >
                      全部
                    </el-button>
                    <el-button
                      @click="formDifficultyclick(key)"
                      :type="
                        formInline.difficulty?.includes(key)
                          ? 'primary'
                          : 'info'
                      "
                      :plain="
                        formInline.difficulty?.includes(key) ? false : true
                      "
                      v-for="(item, key) in questiondifficulty.labelObj"
                      :key="item"
                      size="default"
                    >
                      {{ item }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item
                  class="container-header-form-item"
                  size="default"
                  label="查找题目"
                  :label-width="70"
                >
                  <div class="container-header-form-item-flex">
                    <div>
                      <el-input
                        size=""
                        :style="{ width: '250px' }"
                        v-model.lazy="formInline.name"
                        placeholder="输入题目名或ID搜索"
                      >
                      </el-input>
                      <!-- CF || isVipCF -->
                      <el-input
                        v-show="isRemoteJudge"
                        class="margin-left20"
                        size=""
                        :style="{ width: '250px' }"
                        v-model.lazy="formInline.cfIdType"
                        placeholder="输入CF题目编号搜索 如38A"
                      >
                      </el-input>
                      <el-button
                        class="container-header-form-search-btn"
                        @click="start"
                        type="primary"
                        size="default"
                      >
                        搜索
                      </el-button>
                    </div>
                    <router-link
                      v-if="activeName == TABSNAME.user && getuser?.isAdmin"
                      custom
                      :to="{ name: '修改我的题库' }"
                      v-slot="{ navigate }"
                    >
                      <el-button @click="navigate" type="primary" size="default"
                        >+ 创建我的题目</el-button
                      >
                    </router-link>
                    <div v-if="activeName == TABSNAME.team && getuser?.isAdmin">
                      <el-button
                        size="default"
                        @click="dialogVisibleAddQuestion = true"
                        type="primary"
                      >
                        + 导入团队题目
                      </el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tabs>
        </el-header>
        <el-main class="container-content">
          <el-pagination
            class="pager margin0"
            size="default"
            :page-size="limit"
            :page-sizes="pageSizes"
            :total="totalCount"
            layout="total, sizes, prev, pager, next"
            @current-change="changePage"
            @size-change="handleSizeChange"
            :current-page="Math.floor(offset / limit) + 1"
          >
          </el-pagination>
          <!-- <el-scrollbar> height="90vh" -->
          <el-table
            row-class-name="cursor-pointer"
            :data="questionData"
            stripe
            v-loading="loading"
            width="100%"
            @row-click="rowClick"
            @sort-change="sortChange"
            @row-contextmenu="handleRightClick"
          >
            <template v-slot:empty>
              <el-empty
                image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
              />
            </template>
            <el-table-column
              width="60"
              prop="date"
              label="状态"
              v-if="activeName !== TABSNAME.nopublic"
            >
              <template #default="{ row }">
                <el-icon
                  :color="
                    Number(row.myACcount)
                      ? 'var(--color-cheng)'
                      : 'var(--color-43)'
                  "
                >
                  <Select v-if="Number(row.myACcount)" />
                  <CloseBold v-else-if="Number(row.myUNcount)" />
                  <SemiSelect v-else />
                </el-icon>
              </template>
            </el-table-column>
            <el-table-column
              width="90"
              prop="ID"
              show-overflow-tooltip
              label="题号"
            />
            <!-- CF题号 -->
            <el-table-column
              width="110"
              v-if="isRemoteJudge || isVipCF"
              show-overflow-tooltip
              prop=""
              label="CF题号"
            >
              <template #default="{ row }">
                <span> {{ row.dataformid }}{{ row.codetype }} </span>
              </template>
            </el-table-column>
            <el-table-column width="60" prop="type" label="题型" />
            <el-table-column
              width=""
              min-width="200"
              show-overflow-tooltip
              prop="name"
              label="题目"
            />
            <el-table-column
              width="300"
              prop="questionlabel"
              label="知识点"
              show-overflow-tooltip
              :tooltip-formatter="
                ({ row }) =>
                  row.questionlabel
                    .map(
                      (vo) => getlabel.find((e) => e.ID === vo.labelid)?.name
                    )
                    .join(', ')
              "
            >
              <template #default="{ row }">
                <el-tag
                  class="question-intable-label"
                  text
                  type="primary"
                  effect="plain"
                  size="default"
                  v-for="(vo, keys) in row.questionlabel"
                  :key="`1-${keys}`"
                  @click.stop="setlabelId(vo.labelid)"
                >
                  {{ getlabel.find((e) => e.ID === vo.labelid)?.name }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              show-overflow-tooltip
              prop="difficulty"
              label="难度"
              v-if="activeName !== TABSNAME.nopublic"
            >
              <template #default="{ row }">
                <div
                  v-if="row.difficulty"
                  :class="`difficulty-${row.difficulty}`"
                >
                  {{ row.difficulty ? DATAdifficulty[row.difficulty] : "" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              prop="ACcount"
              v-if="
                activeName !== TABSNAME.match &&
                activeName !== TABSNAME.nopublic
              "
              label="AC次数"
            >
              <template #default="{ row }">
                {{ row.ACcount || 0 }}
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              prop="userquestioncount"
              v-if="
                activeName !== TABSNAME.match &&
                activeName !== TABSNAME.nopublic
              "
              label="提交次数"
            >
              <template #default="{ row }">
                {{ row.userquestioncount || 0 }}
              </template>
            </el-table-column>
            <el-table-column
              width=""
              min-width="100"
              v-if="
                activeName !== TABSNAME.match &&
                activeName !== TABSNAME.nopublic
              "
              label="AC率"
            >
              <template #default="{ row }">
                <el-progress
                  :text-inside="true"
                  :stroke-width="18"
                  :percentage="getACRate(row)"
                  :color="customColors"
                />
              </template>
            </el-table-column>
            <el-table-column
              width=""
              v-if="isVipCF"
              show-overflow-tooltip
              prop="rating"
              label="Rating"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              v-if="activeName == TABSNAME.match"
              width=""
              show-overflow-tooltip
              prop="dataform"
              label="来源"
            >
              <template #default="{ row }">
                <el-link
                  v-if="formInline.source == DATAform.CODEFORCES"
                  @click.navite.stop="() => {}"
                  :href="getCfQuestionUrl(row.dataform)"
                  target="_blank"
                  type="primary"
                >
                  {{ row.dataform }}
                </el-link>
                <span v-else>
                  {{ row.dataform }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              width="160"
              prop=""
              v-if="activeName === TABSNAME.user"
              label="操作"
            >
              <template #default="{ row }">
                <router-link
                  custom
                  :to="{ name: '修改我的题库', query: { ID: row.ID } }"
                  v-slot="{ navigate }"
                >
                  <el-button
                    size="default"
                    type="primary"
                    @click.stop="navigate"
                    >编辑</el-button
                  >
                </router-link>
                <el-button
                  size="default"
                  type="primary"
                  @click.stop="del(row.ID)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            class="pager"
            size="default"
            :page-size="limit"
            :page-sizes="pageSizes"
            :total="totalCount"
            layout="total, sizes, prev, pager, next"
            @current-change="changePage"
            @size-change="handleSizeChange"
            :current-page="Math.floor(offset / limit) + 1"
          >
          </el-pagination>
          <!-- </el-scrollbar> -->
        </el-main>
      </el-container>
      <el-aside class="container-aside">
        <selectlabelVue
          @update:label="grouplabelclick"
          @change:label="groupLabelClose"
          @clear:label="groupLabelClear"
          :label="setlabel"
          :search="start"
        ></selectlabelVue>
      </el-aside>
    </el-container>
    <!-- 添加团队题目 -->
    <el-dialog
      v-model="dialogVisibleAddQuestion"
      v-if="dialogVisibleAddQuestion"
      title="选择题目"
      width="840px"
      height="90vh"
      top="0"
      :before-close="beforeClose"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          选择题目
        </span>
      </template>
      <selectquestionVue
        :addclick="addclick"
        :teamid="teamId"
      ></selectquestionVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CloseBold, Select, SemiSelect } from "@element-plus/icons-vue";
import { useClipboard } from "@vueuse/core";
import { ElMessage, ElMessageBox, TabPaneName } from "element-plus";
import { debounce } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  Iobj,
  Iquestionoption,
  asyncaddquestionteam,
  asyncdelquestion,
  asyncselectquestion,
} from "../../../api";
import { Iquestion, Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { showCF } from "../../../util/data";
import { removeDifficulty } from "../../../util/questionPermissions";
import selectlabelVue from "../../components/selectlabel/aside.vue";
import selectquestionVue from "../../components/selectquestion/question.vue";
import { CFdifficulty, DATAform } from "../../data/data";
import { DATAdifficulty } from "../../../index/data/data";
const { copy } = useClipboard();

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);
console.log("tenant_id", tenant_id);
const isShowAccoder = computed(() => {
  return tenant_id === "码客行";
});

enum TABSNAME {
  public = "public",
  team = "team", // team
  match = "match",
  codeforces = "codeforces",
  user = "user",
  accoder = "accoder",
  nopublic = "nopublic", // 初赛题库
}
const tabsCfg = {
  [TABSNAME.public]: {
    desc: "编程题库：该专题是系统编程题库，所有人都可以访问",
  },
  [TABSNAME.nopublic]: {
    desc: "初赛题库：该专题是系统非编程题库，所有人都可以访问",
  },
  [TABSNAME.team]: {
    desc: "团队题库：该题库是团队内部指定题库，由团队管理员从“我的专题”中授权开放至团队",
  },
  [TABSNAME.match]: {
    desc: "精选题库：该题库只有团队管理员可见，可将该题库中的题目添加到“我的题目”",
  },
  [TABSNAME.codeforces]: { desc: "" },
  [TABSNAME.user]: {
    desc: "我的题目：用于我个人收藏的题目。如果是团队管理员，可以将我的题目开放至团队",
  },
  [TABSNAME.accoder]: { desc: "" },
};

const isRemoteJudge = computed(() => {
  return activeName.value === TABSNAME.codeforces;
});
const isVipCF = computed(() => {
  return (
    activeName.value === TABSNAME.match &&
    formInline.source === DATAform.CODEFORCES
  );
});

// AC 率颜色
const customColors = [
  { color: "#e83828", percentage: 20 },
  { color: "#f0830ac", percentage: 40 },
  { color: "#82bd1c", percentage: 60 },
  { color: "#1ecbb4", percentage: 70 },
  { color: "#4683fa", percentage: 100 },
];
const router = useRouter();
const store = useStore(Storekey);

const getuser = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(getuser.value?.teamid);
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});
// 团队题库分组
const questiondifficulty = computed(() => {
  // 每个团队的 questiondifficulty 合并、并且去重去除undefined
  const hiddenQuestionDifficulty =
    getteam.value
      ?.map((e) => e?.questiondifficulty || [])
      .flat()
      .filter((e) => e) || [];
  return removeDifficulty(DATAdifficulty, hiddenQuestionDifficulty);
});

const showRemotejudge = computed(() => {
  return getteam.value.some((c) => c?.other?.showRemotejudge);
});
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const vip = computed(() => {
  return getuser.value?.uservip?.length;
  // return getuser.value?.uservip?.find(c => c.viplistid === 1)
});

const formInline = reactive<
  Iobj<Studycodemodel.Iquestion & { ratingSort: string; cfIdType: string }>
>({
  teamid: getteam.value.map((e) => e.ID),
  name: "",
  // label: "",
  ratingSort: "ASC",
  cfIdType: "",
});
// 监听 getteam 的变化，更新 formInline.teamid
watch(
  getteam,
  (newTeam) => {
    formInline.teamid = newTeam.map((e) => e.ID); // 更新 teamid
  },
  { immediate: true }
); // immediate 确保初始化时同步一次

// CF搜索相关
const dataformid = computed(() => {
  if (!formInline.cfIdType) {
    return undefined;
  }
  // 匹配以数字开头的部分
  return formInline.cfIdType.match(/^\d+/)?.[0] || undefined;
});
const codetype = computed(() => {
  if (!formInline.cfIdType) {
    return undefined;
  }
  // 匹配非数字部分及其后面的数字（如果有）
  return formInline.cfIdType.match(/[A-Za-z]\d*$/)?.[0] || undefined;
});

const setlabel = ref<number[]>([]);
function setlabelId(labelId?: number) {
  if (labelId) {
    setlabel.value.splice(0, setlabel.value.length, labelId);
  }
}
function grouplabelclick(item: number) {
  const i = setlabel.value.findIndex((e) => e === item);
  if (i != -1) {
    setlabel.value.splice(i, 1);
  } else {
    setlabel.value.push(item);
  }
}
function groupLabelClose(i: number) {
  setlabel.value.splice(i, 1);
}
function groupLabelClear() {
  // 响应式数组清空
  setlabel.value.length = 0;
}
watch(setlabel.value, () => {
  start();
});

const route = useRoute();
const routeQuery = computed(() => {
  return route.query as Record<string, string>;
});
const order = computed(() => {
  return (routeQuery.value.order ||
    "ID") as string as keyof Studycodemodel.Iquestion;
});

const loading = ref(true);
const offset = ref(0);
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500];
const sortable = computed(() => {
  return (routeQuery.value.sortable || "ASC") as "DESC" | "ASC";
});

function reset() {
  formInline.name = undefined;
  formInline.cfIdType = "";
  formInline.difficulty = undefined;
  formInline.rating = undefined;
  formInline.source = undefined;
  // 响应式数组清空
  setlabel.value.length = 0;
  //
  offset.value = 0;
  limit.value = 20;
  start();
}
const stretch = ref(false);
const activeName = ref<TABSNAME>(TABSNAME.public);
function tabChange(v: TabPaneName) {
  reset();
  router.push({ query: { tabName: v } });
}

// AC率
function getACRate(row: Iquestion) {
  return row.userquestioncount
    ? Math.floor(
        (Number(row.ACcount || 0) / Number(row.userquestioncount)) * 100
      )
    : 0;
}
function getCfQuestionUrl(v: string = "") {
  v = v || "";
  let url = "https://codeforces.com/problemset/problem";
  let str = v.split("-")[0].replace("CF", "");
  let path1 = str.slice(0, str.length - 1);
  let path2 = str.slice(str.length - 1);
  return `${url}/${path1}/${path2}`;
}
// 表格点击跳转
function rowClick(row: Iquestion, column: any, event: Event) {
  const routeUrl = router.resolve({
    name: "题目",
    params: { ID: row.ID },
    query: {
      order: order.value,
      offset: offset.value,
      limit: limit.value,
      teamid:
        activeName.value === TABSNAME.team
          ? formInline.teamid.length
            ? formInline.teamid
            : getteam.value?.map((v) => v.ID)
          : null,
      // 搜索条件
      name: formInline.name,
      range:
        activeName.value === TABSNAME.team ? TABSNAME.public : activeName.value,
      setlabel: setlabel.value,
      difficulty: formInline.difficulty,
      rating: formInline.rating,
      source: formInline.source,
      userid: activeName.value === TABSNAME.user ? getuser.value?.ID : null,
      // CF
      dataformid: dataformid.value,
      codetype: codetype.value,
      // Vip CF
      dataform: formInline.cfIdType,
    },
  });
  window.open(routeUrl.href, "_blank");
}
// 处理右键点击事件
function handleRightClick(row: any, column: any, event: Event) {
  // 获取该行的目标链接
  const questionUrl = getQuestionUrl(row);
  console.log("右键点击了题目:", row.name, "链接为:", questionUrl);
  copy(questionUrl);
}
function getQuestionUrl(row: Iquestion) {
  const data = {
    name: "题目",
    params: { ID: row.ID },
    query: {
      order: order.value,
      offset: offset.value,
      limit: limit.value,
      teamid:
        activeName.value === TABSNAME.team
          ? formInline.teamid.length
            ? formInline.teamid
            : getteam.value?.map((v) => v.ID)
          : null,
      name: formInline.name,
      range:
        activeName.value === TABSNAME.team ? TABSNAME.public : activeName.value,
      setlabel: setlabel.value,
      difficulty: formInline.difficulty,
      rating: formInline.rating,
      source: formInline.source,
      userid: activeName.value === TABSNAME.user ? getuser.value?.ID : null,
      dataformid: dataformid.value,
      codetype: codetype.value,
      dataform: formInline.cfIdType,
    },
  };
  const resolvedUrl = router.resolve(data);
  // 获取当前页面的协议和域名部分
  const { pathname, origin } = window.location;
  return `${origin}${pathname}${resolvedUrl.href}`;
}

// 排序
function sortChange(data: {
  column: any;
  prop: string;
  order: "ascending" | "descending" | null;
}) {
  let sort = data.order === "descending" ? "DESC" : "ASC";
  formInline.ratingSort = sort;
}

watch(formInline, () => {
  start();
});
const debouncet1 = ref<Function>();

const tabName = computed(() => {
  return (route.query.tabName as TABSNAME) || TABSNAME.public;
});
watch(tabName, () => {
  activeName.value = TABSNAME[tabName.value];
});

onMounted(() => {
  // 是否跳转
  if (tabName.value) {
    activeName.value = TABSNAME[tabName.value];
  }
  store.dispatch("actionlabel");
  debouncet1.value = debouncet();
  start();
});

const questionData = ref<Studycodemodel.Iquestion[]>([]);
const totalCount = ref(0);
function debouncet() {
  return debounce(async () => {
    const { name, ratingSort } = formInline;
    const obj: Iobj<Iquestionoption> = {
      _order: ["rating", order.value],
      _sortable: ratingSort ? ratingSort : sortable.value || "ASC",
      _offset: offset.value,
      _limit: limit.value,
      type: "代码",
    };
    let _like: [keyof Studycodemodel.Iquestion, any];
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    let t;
    // 公开题库
    if (activeName.value === TABSNAME.public) {
      obj.range = TABSNAME.public;
      // RemoteJudge
    } else if (activeName.value === TABSNAME.nopublic) {
      obj.type = ["填空", "单选", "多选", "判断"];
      obj.range = TABSNAME.public;
    } else if (isRemoteJudge.value) {
      obj.range = TABSNAME.codeforces;
      obj.dataformid = dataformid.value;
      obj.codetype = codetype.value;
      // 精选题库
    } else if (activeName.value === TABSNAME.match) {
      obj.range = TABSNAME.match;
      if (formInline.source) {
        obj.source = formInline.source;
      }
      // 来源 dataform 中模糊匹配的是 cf Rating
      if (isVipCF.value && formInline.rating) {
        obj.rating = formInline.rating;
      }
      // Vip CF
      if (isVipCF.value && formInline.cfIdType) {
        obj.dataformid = dataformid.value;
        obj.codetype = codetype.value;
      }
    } else if (activeName.value === TABSNAME.user) {
      obj.range = TABSNAME.user;
      obj.userid = getuser.value?.ID;
    } else if (activeName.value === TABSNAME.accoder) {
      obj.range = TABSNAME.accoder;
    } else {
      //  t = teamid.length ? teamid : getteam.value?.map((v) => v.ID);
      t = getteam.value?.map((v) => v.ID);
      obj.teamid = t;
    }
    if (!obj.range) {
      // 团队题库 暂时不需要public 不然 个人题目显示不了
      // obj.range = TABSNAME.public
    }
    if (
      formInline.source != DATAform.CODEFORCES &&
      Array.isArray(formInline.difficulty) &&
      formInline.difficulty.length
    ) {
      obj.difficulty = formInline.difficulty;
    }
    if (setlabel.value && setlabel.value.length) {
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = ["labelid", setlabel.value];
    }
    loading.value = true;
    const { count, rows } = await asyncselectquestion(obj);
    questionData.value = rows;
    totalCount.value = count;
    loading.value = false;
  }, 300);
}
function start() {
  if (debouncet1.value) {
    debouncet1.value();
  }
}

function formDifficultyclick(item: string) {
  if (!Array.isArray(formInline.difficulty)) formInline.difficulty = [];
  const i = formInline.difficulty.findIndex((e: string) => e === item);
  if (i != -1) {
    formInline.difficulty.splice(i, 1);
  } else {
    formInline.difficulty.push(item);
  }
}
function sourceClick(item: string) {
  formInline.source = item;
}

function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
  start();
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};

async function del(ID?: number) {
  if (ID) {
    ElMessageBox.confirm("你确定要删除此题吗", "提示").then(async () => {
      try {
        await asyncdelquestion({ ID });
        ElMessage.success("删除成功");
        start();
      } catch (e: any) {
        ElMessage.error(e);
      }
    });
  }
}

// 添加题目
const dialogVisibleAddQuestion = ref(false);
async function addclick(v: Studycodemodel.Iquestionbank) {
  await asyncaddquestionteam({ questionid: v.ID, teamid: teamId.value })
    .then(() => {
      ElMessage.success("添加成功");
      dialogVisibleAddQuestion.value = false;
    })
    .catch((f) => {
      ElMessage.error(f);
    });
}
function beforeClose() {
  start();
  dialogVisibleAddQuestion.value = false;
}
</script>

<style scoped>
.container-box {
  /* 是否固定表格列表 */
  min-height: calc(100vh - 90px);
  /* max-height: calc(100vh - 90px); */

  /* margin-top: 20px; */
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 23vh;
  --container-bg-color: #fff;
}

.container-left {
  margin-right: var(--container-margin);
}

.container-header {
  width: 100%;
  padding: 0;
}

.container-header-form {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  /* height: calc(var(--container-header-height) - var(--el-tabs-item-height)); */
  height: auto;
  padding: 10px 0 15px 0;
}

.container-header-form-item {
  font-weight: 700;
  text-align: left;
  margin: 10px 0;
  --color-43: #000;
}

.container-header-form-item .el-button.is-text {
  border-width: 1px;
}

.container-header-form-item .el-button--default:active {
  border-color: transparent;
}

.container-header-form-item-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.container-content {
  margin-top: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 80%;
}

.container-content .pager {
  margin: var(--container-margin);
  margin-right: 0;
  margin-bottom: 0;
  float: right;
}

.container-aside {
  min-width: 25%;
  background: var(--container-bg-color);
}
</style>

<style>
.el-button.is-text {
  border-width: 1px;
}
</style>
